package com.pay.ioopos.support.serialport.custom;

import com.pay.ioopos.support.serialport.CmdParamException;
import com.pay.ioopos.support.utils.BigDecimalUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

/**
 * 输出指令：发起收款
 * @author moyq5
 * @since 2022/7/26
 * @see SerialPortPayCmd4SubmitDer
 */
public class SerialPortPayCmd2Submit extends SerialPortPayCmdAbstract {
    private static int serialNo = 0;

    private BigDecimal amount;
    private String orderNo;
    /**
     *
     * @param amount 收款金额，单位：元
     */
    public SerialPortPayCmd2Submit(BigDecimal amount) {
        this.amount = amount;
    }

    @Override
    protected CustomCmdAckType ackType() {
        return CustomCmdAckType.REQ;
    }

    @Override
    protected SerialPortPayCmdType bizType() {
        return SerialPortPayCmdType.PAY_SUBMIT;
    }

    @Override
    protected int serialNo() {
        if (serialNo > 0xFFFF) {
            serialNo = 0;
        }
        return serialNo++;
    }

    @Override
    protected byte[] content() {
        if (null == amount) {
            throw new CmdParamException("金额不能为空");
        }
        int fen = BigDecimalUtils.yuanToFen(amount);
        if (fen <= 0) {
            throw new CmdParamException("金额无效");
        }
        if (fen > 0xFFFFFF) {
            throw new CmdParamException("金额超上限：" + BigDecimalUtils.fenToYuan(0xFFFFFF));
        }

        // 单号
        byte[] orderNos = new byte[0];
        if (null != orderNo && !orderNo.isEmpty()) {
            orderNos = orderNo.getBytes(StandardCharsets.UTF_8);
        }
        if (orderNos.length > 0xFF) {
            throw new CmdParamException("单号过长：" + orderNos.length);
        }

        // 金额（3）+ 单号长度值（1）+ 单号长度
        byte[] content = new byte[4 + orderNos.length];

        // 金额，分表示值，3个字节，高位在前
        content[0] = (byte) ((fen >> 16) & 0xFF);
        content[1] = (byte) ((fen >> 8) & 0xFF);
        content[2] = (byte) (fen & 0xFF);

        // 单号长度，1字节
        content[3] = (byte) (orderNos.length & 0xFF);
        // 单号
        if (orderNos.length > 0) {
            System.arraycopy(orderNos, 0, content, 4, orderNos.length);
        }

        return content;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

}
